#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import os, time

from icewood import tinylog

from icewood.jancab.filecell import FileCell


class   TestFileCell(object) :
    
    def __init__(self, data_dir) :
        self.data_dir = os.sep.join((data_dir, 'filecell'))
        ## __init__()

    def setUp(self) :
        if os.path.exists( self.data_dir ) :
            self.removedirs( self.data_dir )
        os.makedirs( self.data_dir, 0777 )

        self.cell = FileCell( path=self.data_dir )
        self.cell.setSwitchThreshold( 1048576 )
        ## setUp()

    def tearDown(self) :
        self.cell.close()
        self.cell = None
        ## tearDown()

    def removedirs(self, path) :
        items = os.listdir(path)
        for name in items :
            fullpath = os.sep.join((path, name))
            if os.path.isdir(fullpath) :
                self.removedirs(fullpath)
            else :
                os.remove(fullpath)

        os.rmdir(path)
        ## removedirs

    def test_001(self) :
        '''test basic read and write
        '''
        location_hello = self.cell.getLocation()
        str_hello = 'HELLO'
        self.cell.write(str_hello, location_hello)
        print 'write',str_hello,'to',location_hello

        location_world = self.cell.getLocation()
        str_world = 'WORLD'
        self.cell.write(str_world, location_world)
        print 'write',str_world,'to',location_world

        s = self.cell.read( location_hello )
        assert( s == str_hello )
        s = self.cell.read( location_world )
        assert( s == str_world )
        ## test_001()

    def test_002(self) :
        '''test switch function
        '''
        data_suffix = 'A' * 1024
        TIMES = 3072

        print 'Test002 : testing WRITE ...'
        time_start = time.time()
        for i in xrange(TIMES) :
            data_prefix = 'HELLO-%09d' % i
            data = '-'.join((data_prefix, data_suffix))
            self.cell.write( data )
        time_last = time.time() - time_start    
        tps = TIMES / time_last
        bw = tps * len(data_suffix) / 1048576.0
        print '        WRITE %d times last %.2f seconds, tps:%.2f, bw:%.2f MB/s' % (TIMES, time_last, tps, bw)
        print 'Test002 : testing WRITE done.'

        print 'Test002 : testing READ ...'
        time_start = time.time()
        for i in xrange(TIMES) :
            data_prefix = 'HELLO-%09d' % i
            data_want = '-'.join((data_prefix, data_suffix))
            data = self.cell.read()
            if data != data_want :
                raise RuntimeError, 'DATA got %r, but want %r' % (data, data_want)
        time_last = time.time() - time_start    
        tps = TIMES / time_last
        bw = tps * len(data_suffix) / 1048576.0
        print '        READ %d times last %.2f seconds, tps:%.2f, bw:%.2f MB/s' % (TIMES, time_last, tps, bw)
        print 'Test002 : testing READ done.'

        
        ## test_002()

    def test_003(self) :
        '''test switch function
        '''
        data_suffix = 'A' * 1024
        TIMES = 8196

        self.cell.setCapacity( 1024 * 1024 * 3 )

        print 'Test003 : testing WRITE ...'
        time_start = time.time()
        for i in xrange(TIMES) :
            data_prefix = 'HELLO-%09d' % i
            data = '-'.join((data_prefix, data_suffix))
            self.cell.write( data )
        time_last = time.time() - time_start    
        tps = TIMES / time_last
        bw = tps * len(data_suffix) / 1048576.0
        print '        WRITE %d times last %.2f seconds, tps:%.2f, bw:%.2f MB/s' % (TIMES, time_last, tps, bw)
        print 'Test003 : testing WRITE done.'

        print 'Test003 : testing READ ...'
        data = self.cell.read()
        skipping = True
        skip_count = 0
        time_start = time.time()
        for i in xrange(TIMES) :
            data_prefix = 'HELLO-%09d' % i
            data_want = '-'.join((data_prefix, data_suffix))
            if skipping :
                if data == data_want :
                    skipping = False
                else :
                    skip_count += 1
                continue

            data = self.cell.read()
            if data != data_want :
                raise RuntimeError, 'DATA got %r, but want %r' % (data, data_want)
        time_last = time.time() - time_start    
        tps = TIMES / time_last
        bw = tps * len(data_suffix) / 1048576.0
        print '        READ %d times last %.2f seconds, tps:%.2f, bw:%.2f MB/s (SKIPPED %d records)' % (TIMES, time_last, tps, bw, skip_count)
        print 'Test003 : testing READ done.'
        ## test_003()


    def run(self) :
        self.setUp()
        self.test_001()
        self.tearDown()

        self.setUp()
        self.test_002()
        self.tearDown()

        self.setUp()
        self.test_003()
        self.tearDown()

        ## run()

    ## class TestFileCell

if __name__ == '__main__' :

    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("", "--data-dir", dest="data_dir", type="string", 
                        help='path to data directory')

    parser.add_option("-l", "--logconf", dest="logconfig", type="string",
                        help='path to logging configure file')

    parser.add_option("-d", "--debug", dest="debug", action="store_true", default=False,
                        help='show debug information')

    (options, args) = parser.parse_args()
    if not options.data_dir :
        parser.print_help( sys.stdout )
        sys.exit(0)

    if options.logconfig :
        tinylog.loadConfigure( options.logconfig )

    if options.debug :
        logger = tinylog.getLogger()
        logger.setLevel(logging.LEVEL_DEBUG)

    t = TestFileCell( options.data_dir )
    t.run()


